package com.mchat.communication.server.initializer;

import com.mchat.communication.server.handler.ImIdleHandler;
import com.mchat.communication.server.handler.WebSocketHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class CustomChannelInitializer extends ChannelInitializer<SocketChannel> {
    public static final int MAX_CONTENT_LENGTH = 65536 * 5;
    @Resource
    private WebSocketHandler webSocketHandler;

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        pipeline.addLast("idle", new ImIdleHandler(3600, 3600, 3600)); // 心跳检测
        pipeline.addLast("http-codec", new HttpServerCodec()); // Http消息编码解码
        pipeline.addLast("aggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH)); // Http消息组装
        pipeline.addLast("http-chunked", new ChunkedWriteHandler()); // WebSocket通信支持
        //http请求的业务逻辑处理
        pipeline.addLast("handler", webSocketHandler); // WebSocket服务端Handler
        pipeline.addLast(
                new WebSocketServerProtocolHandler("/", null, false, MAX_CONTENT_LENGTH)
        );
    }
}
